/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package des;

import javax.swing.JOptionPane;
import javax.swing.JTextArea;

/**
 *
 * @author morfant
 */
public class DESFrame extends javax.swing.JFrame {

    private DESCypher desCypher = new DESCypher();

    /**
     * Creates new form DESFrame
     */
    public DESFrame() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        textForEncrypt = new javax.swing.JTextArea();
        jScrollPane2 = new javax.swing.JScrollPane();
        resultOfEncrypt = new javax.swing.JTextArea();
        jScrollPane3 = new javax.swing.JScrollPane();
        textForDecrypt = new javax.swing.JTextArea();
        jScrollPane4 = new javax.swing.JScrollPane();
        resultOfDecrypt = new javax.swing.JTextArea();
        passTextField = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        encryptButton = new javax.swing.JButton();
        copyResultOfEncryptButton = new javax.swing.JButton();
        decryptButton = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        textForEncrypt.setColumns(20);
        textForEncrypt.setLineWrap(true);
        textForEncrypt.setRows(5);
        textForEncrypt.setMinimumSize(new java.awt.Dimension(100, 60));
        textForEncrypt.setPreferredSize(null);
        jScrollPane1.setViewportView(textForEncrypt);

        resultOfEncrypt.setColumns(20);
        resultOfEncrypt.setEditable(false);
        resultOfEncrypt.setLineWrap(true);
        resultOfEncrypt.setRows(5);
        resultOfEncrypt.setMinimumSize(new java.awt.Dimension(100, 60));
        resultOfEncrypt.setPreferredSize(null);
        jScrollPane2.setViewportView(resultOfEncrypt);

        textForDecrypt.setColumns(20);
        textForDecrypt.setLineWrap(true);
        textForDecrypt.setRows(5);
        textForDecrypt.setMinimumSize(new java.awt.Dimension(100, 60));
        textForDecrypt.setPreferredSize(null);
        jScrollPane3.setViewportView(textForDecrypt);

        resultOfDecrypt.setColumns(20);
        resultOfDecrypt.setEditable(false);
        resultOfDecrypt.setLineWrap(true);
        resultOfDecrypt.setRows(5);
        resultOfDecrypt.setMinimumSize(new java.awt.Dimension(100, 60));
        resultOfDecrypt.setPreferredSize(null);
        jScrollPane4.setViewportView(resultOfDecrypt);

        passTextField.setHorizontalAlignment(javax.swing.JTextField.CENTER);

        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Пароль");

        encryptButton.setText("<html>Зашифровать</html>");
        encryptButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                encryptButtonActionPerformed(evt);
            }
        });

        copyResultOfEncryptButton.setText("<html>Скопировать<br>результат<br>шифрования</html>");
        copyResultOfEncryptButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                copyResultOfEncryptButtonActionPerformed(evt);
            }
        });

        decryptButton.setText("<html>Дешифровать</html>");
        decryptButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                decryptButtonActionPerformed(evt);
            }
        });

        jLabel2.setText("Текст для шифрования");

        jLabel3.setText("Результат шифрования");

        jLabel4.setText("Текст для дешифрования");

        jLabel5.setText("Результат дешифрования");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(95, 95, 95)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(jLabel4)
                    .addComponent(jScrollPane3)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 182, Short.MAX_VALUE)
                    .addComponent(jLabel2))
                .addGap(40, 40, 40)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(passTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(encryptButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(decryptButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(copyResultOfEncryptButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(36, 36, 36)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(jLabel5)
                    .addComponent(jLabel3)
                    .addComponent(jScrollPane2)
                    .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 175, Short.MAX_VALUE))
                .addGap(90, 90, 90))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(23, 23, 23)
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(passTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(49, 49, 49)
                        .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(94, 94, 94)
                        .addComponent(encryptButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(91, 91, 91)
                        .addComponent(copyResultOfEncryptButton))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane1)
                            .addComponent(jScrollPane2))
                        .addGap(47, 47, 47)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel5)
                            .addComponent(jLabel4))))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(96, 96, 96)
                        .addComponent(decryptButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 157, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jScrollPane4)
                            .addComponent(jScrollPane3))
                        .addGap(95, 95, 95))))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void encryptButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_encryptButtonActionPerformed
        try {
            String pass = passTextField.getText();
            String message = textForEncrypt.getText();
            String result = encryptMessage(pass, message);
            resultOfEncrypt.replaceRange(result, 0, resultOfEncrypt.getText().length());
            resultOfEncrypt.setCaretPosition(0);
        } catch (IllegalArgumentException e) {
            printErrorMessage(e);
        }
    }//GEN-LAST:event_encryptButtonActionPerformed

    private void copyResultOfEncryptButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_copyResultOfEncryptButtonActionPerformed
        String copyMessage = resultOfEncrypt.getText();
        if ((copyMessage != null) && (!"".equals(copyMessage))) {
            textForDecrypt.replaceRange(copyMessage, 0, textForDecrypt.getText().length());
            textForDecrypt.setCaretPosition(0);
        }
    }//GEN-LAST:event_copyResultOfEncryptButtonActionPerformed

    private void decryptButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_decryptButtonActionPerformed
        try {
            String pass = passTextField.getText();
            String message = textForDecrypt.getText().toUpperCase();
            String result = decryptMessage(pass, message);
            resultOfDecrypt.replaceRange(result, 0, resultOfDecrypt.getText().length());
            resultOfDecrypt.setCaretPosition(0);
        } catch (IllegalArgumentException e) {
            printErrorMessage(e);
        }
    }//GEN-LAST:event_decryptButtonActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(DESFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(DESFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(DESFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(DESFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new DESFrame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton copyResultOfEncryptButton;
    private javax.swing.JButton decryptButton;
    private javax.swing.JButton encryptButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JTextField passTextField;
    private javax.swing.JTextArea resultOfDecrypt;
    private javax.swing.JTextArea resultOfEncrypt;
    private javax.swing.JTextArea textForDecrypt;
    private javax.swing.JTextArea textForEncrypt;
    // End of variables declaration//GEN-END:variables

    private String encryptMessage(String pass, String message) {
        return byteArrayToHEXString(desCypher.encrypteMessage(pass.getBytes(), message.getBytes()));
    }

    private String decryptMessage(String pass, String message) {
        if (checkStringForHEXFormat(message)) {
            if (message.length() % 2 == 0) {
                return new String(desCypher.decryptMessage(pass.getBytes(), hexStringToByteArray(message)));
            } else {
                throw new IllegalArgumentException("Строка для дешифровки имеет ошибки. HEX формат нарушен.");
            }
        } else {
            throw new IllegalArgumentException("Строка для дешифровки имеет ошибки. HEX формат нарушен.");
        }
    }
    /**
     * Массив соответствий значений байта и его 16 ричного представления.
     * Используется для печати данных.
     */
    private static final byte[] HEX_CHAR_TABLE = {
        (byte) '0', (byte) '1', (byte) '2', (byte) '3',
        (byte) '4', (byte) '5', (byte) '6', (byte) '7',
        (byte) '8', (byte) '9', (byte) 'A', (byte) 'B',
        (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F'
    };
    /**
     * Строка паттерн для проверки соответствия строки шестрадцатиричному
     * формату записи цифр.
     */
    private static final String HEX_CHAR_STRING = "0123456789ABDCEF";

    /**
     * Метод, которые преобразует байт в строку в 16 формате.
     *
     * @param bt Байт
     * @return Строка со значением байта в 16 ричном формате.
     */
    public String byteToHexString(byte bt) {
        int index = bt & 0xFF;//Присваивание байта к инту в беззнаковой форме.
        StringBuilder hexString = new StringBuilder();
        hexString.append((char) HEX_CHAR_TABLE[index >> 4]);//Первые 4 бита байта.
        hexString.append((char) HEX_CHAR_TABLE[index & 0xF]);//Вторые 4 бита байта.
        return hexString.toString();
    }

    /**
     * Распечатка массива байтов в консоль в 16 ричном формате.
     *
     * @param byteArray Массив байтов.
     */
    public String byteArrayToHEXString(byte[] byteArray) {
        int length = byteArray.length;
        String result = "";
        for (int i = 0; i < length; i++) {
            result += byteToHexString(byteArray[i]);
        }
        return result;
    }

    /**
     * Метод, который трансформирует строку с цифрами в HEX формате в массив
     * байтов.
     *
     * @param s Строка в HEX формате.
     * @return Массив байтов.
     */
    public static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                    + Character.digit(s.charAt(i + 1), 16));
        }
        return data;
    }

    private boolean checkStringForHEXFormat(String message) {
        int lenght = message.length();
        boolean isHEX = true;
        int i = 0;
        while ((isHEX) && (i < lenght)) {
            isHEX = (HEX_CHAR_STRING.lastIndexOf(message.charAt(i)) != -1 ? true : false);
            i++;
        }

        return isHEX;
    }

    private void printErrorMessage(Exception exc) {
        JOptionPane.showMessageDialog(null, exc.getMessage(), "Error",
                JOptionPane.ERROR_MESSAGE);
    }
}
